<template>
  <div class="condition-setting">
    <div v-if="conditionList && conditionList.length" class="condition">
      <div class="condition-header" v-if="isShowFirstCondition">
        <span> 逻辑条件： </span>
        <Select v-model:value="selectValue" style="width: 274px" :options="logicalConditions" />
      </div>
      <div class="condition-content mt-4">
        <ConditionTree
          v-if="conditionListBoolean"
          v-model:selectedKeys="selectedKeys"
          class="condition-tree"
          draggable
          :conditionList="conditionList"
          @select="handleSelect"
          @create="handleCreate"
          @delete="handleDelete"
        />
      </div>
    </div>
    <div v-else class="condition-empty">
      <img src="../../../../../../assets/images/table-empty.png" alt="" />
      <div class="text">暂无条件设置</div>
      <Button class="mt-4" type="primary" ghost @click="handleAddFirstCondition">添加新条件</Button>
    </div>
    <div
      v-if="conditionList && conditionList.length"
      class="condition-modal"
      :style="{ left: modalLeft }"
    >
      <ConditionDrawer
        :itemObj="itemObj"
        @close="handleAddCancel"
        :tabSiderType="tabSiderType"
        :tabType="tabType"
        ref="ConditionSet"
      >
        <template #footer>
          <div class="footer">
            <a-button class="button" size="large" @click="handleAddCancel">取消</a-button>
            <!-- <a-button class="button" size="large" type="primary" ghost @click="handleEmpty"> 清空</a-button> -->
            <a-button class="button" type="primary" size="large" @click="handleAddSubmit"
              >确认</a-button
            >
          </div>
        </template>
      </ConditionDrawer>
    </div>
    <div class="mask" v-if="selectedItemId"></div>
  </div>
</template>
<script lang="ts" setup name="Condition">
  import { computed, ref, watch, nextTick } from 'vue';
  import { Select, Button } from 'ant-design-vue';
  import {
    logicalConditions,
    conditionItemDefault,
    compareTypeOptions,
    activityFNTypeList,
  } from './condition.data';
  import ConditionDrawer from './ConditionDrawer.vue';
  import modelerStore from '/@/store/modules/bpmnModeler';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '/@/hooks/web/useMessage';
  import ConditionTree from './ConditionTree.vue';
  defineProps({
    tabSiderType: Number,
    tabType: Number,
  });
  const { createMessage } = useMessage();
  const conditionListBoolean = ref(true);
  const modeler = modelerStore();
  const flowInfo = computed(() => modeler.getFlowInfo);
  const selectValue = ref(1);
  const conditionItem = ref<any>({});
  const conditionItemBase = {
    conditionName: '或(只需有一个条件成立)',
    conditionId: 1,
    key: 1,
    conditionType: 1,
    children: [] as any,
    activityFNType: null,
    responseChoice: null,
    compareType: null,
    compareContent: '',
    tumTrfType: 0,
    sourceActivityId: -1,
    bindPropName: null,
  };

  const conditionList = ref<any>([]);
  const modalLeft = ref('0px');
  const selectedItemId = ref(null);
  const selectedKeys = ref([]);
  let itemObj = ref<any>({});
  function findSelectedItem(arr) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].conditionId === selectedItemId.value) {
        itemObj.value = cloneDeep(arr[i]);
      } else {
        if (arr[i].children && arr[i].children.length > 0) {
          findSelectedItem(arr[i].children);
        }
      }
    }
    // let item = arr.find((i) => i.conditionId === selectedItemId.value);
  }

  function updateSelectedItem(arr, item) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].conditionId === selectedItemId.value) {
        arr[i] = { ...item };
      } else {
        if (arr[i].children && arr[i].children.length > 0) {
          updateSelectedItem(arr[i].children, item);
        }
      }
    }
  }
  function deleteSelectedItem(arr, id, level) {
    if (level === 0) {
      conditionList.value = [];
      return;
    }
    arr.forEach((item) => {
      if (item.level === level - 1) {
        const index = item.children.findIndex((i) => i.conditionId === id);
        item.children.splice(index, 1);
      } else {
        if (item.children && item.children.length > 0) {
          deleteSelectedItem(item.children, id, level);
        }
      }
    });
  }
  function setConditionName(arr) {
    arr.forEach((item) => {
      item.conditionName = sumConditionName(item);
      if (item.children && item.children.length > 0) {
        setConditionName(item.children);
      }
    });
  }
  // 第一次添加新条件
  function handleAddFirstCondition() {
    selectValue.value = 1;

    conditionItem.value = cloneDeep(conditionItemBase);
    conditionList.value = [conditionItem.value];
  }
  const isShowFirstCondition = ref(false);
  //点击某一项
  async function handleSelect(selectedKeys, e) {
    console.log(e);

    if (selectedKeys.length && e.node.conditionId === 1) {
      isShowFirstCondition.value = true;
    } else {
      isShowFirstCondition.value = false;
    }

    if (selectedKeys.length && e.node.conditionId !== 1) {
      selectedItemId.value = e.node.conditionId;
      modalLeft.value = '-520px';
      findSelectedItem(conditionList.value);

      if (itemObj.value.conditionType === 0) {
        ConditionSet.value.activeKey = 1;
        console.log(
          '%c ConditionSet.value===>167： ',
          'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
          ConditionSet.value,
          itemObj.value,
        );

        await ConditionSet.value.setFieldsValueStep({
          ...itemObj.value,
          sourceActivityId: itemObj.value.sourceActivityId,
          activityFNType: itemObj.value.activityFNType,
        });
      } else if (itemObj.value.conditionType === 1 || itemObj.value.conditionType === 2) {
        ConditionSet.value.activeKey = 2;
        ConditionSet.value.setFieldsValueLogic({ ...itemObj.value });
      } else if (itemObj.value.conditionType === 3) {
        //const value = itemObj.value.compareType;
        ConditionSet.value.activeKey = 3;

        ConditionSet.value.setFieldsValueControlForm({
          ...itemObj.value,
        });
      } else {
        ConditionSet.value.activeKey = 1;

        await ConditionSet.value.setFieldsValueStep({ ...itemObj.value });
        ConditionSet.value.setFieldsValueLogic({ ...itemObj.value });
        ConditionSet.value.setFieldsValueControlForm({ ...itemObj.value });
        ConditionSet.value.clearValidateStep();
        ConditionSet.value.clearValidateLogic();
        ConditionSet.value.clearValidateControlForm();
      }
    } else {
      selectedItemId.value = null;
      modalLeft.value = '0px';
    }
  }
  //点击新条件
  function handleCreate(item) {
    flowInfo.value.conditionMaxId++;
    if (item.level === 0) {
      selectedItemId.value = null;
    } else {
      selectedItemId.value = item.conditionId;
    }
    findSelectedItem(conditionList.value);
    if (selectedItemId.value) {
      if (itemObj.value.conditionType === 1 || itemObj.value.conditionType === 2) {
        //新增非根节点的子条件
        itemObj.value.children.push({
          conditionName: '新条件',
          conditionType: null,
          children: [] as any,
          activityFNType: null,
          responseChoice: null,
          compareType: null,
          compareContent: '',
          tumTrfType: 0,
          sourceActivityId: null,
          bindPropName: null,
          key: flowInfo.value.conditionMaxId,
          conditionId: flowInfo.value.conditionMaxId,
        });
        updateSelectedItem(conditionList.value, itemObj.value);
      }
    } else {
      // 新增根节点的字条件
      conditionItem.value.children.push({
        ...conditionItemDefault,
        key: flowInfo.value.conditionMaxId,
        conditionId: flowInfo.value.conditionMaxId,
      });
      conditionList.value = [conditionItem.value];
    }
    selectedItemId.value = null;
    modalLeft.value = '0px';
    conditionListBoolean.value = false;
    nextTick(() => {
      conditionListBoolean.value = true;
    });
  }

  function handleDelete(item) {
    deleteSelectedItem(conditionList.value, item.conditionId, item.level);
    nodeItem.value.condition = conditionList.value[0];
    handleAddCancel();
  }

  const ConditionSet = ref<any>(null);
  function sumConditionName(condition) {
    if (condition.conditionType === 0) {
      let sourceActivityName = findActivityName(condition.sourceActivityId);

      let activityName = activityFNTypeList[condition.activityFNType]?.label || '';
      let compareName = compareTypeOptions[condition.compareType]?.label || '';
      return `步骤【${sourceActivityName}】${condition.responseChoice ? '意见为' : ''} ${
        condition.responseChoice || ''
      } ${activityName} ${compareName} ${condition?.compareContent || ''}${
        condition.activityFNType === 2 || condition.activityFNType === 4 ? '人' : ''
      }${condition.activityFNType === 3 || condition.activityFNType === 5 ? '%' : ''}`;
    } else if (condition.conditionType === 1 || condition.conditionType === 2) {
      return condition.conditionType === 1
        ? '或(只需有一个条件成立)'
        : '且(只有当前步骤触发的条件成立)';
    } else if (condition.conditionType === 3) {
      let compareName = compareTypeOptions[condition.compareType]?.label || '';

      return `表头【${condition.bindPropName}】${compareName}${condition.compareContent}`;
    } else {
      return condition?.conditionName || '';
    }
  }
  async function handleAddSubmit() {
    if (ConditionSet.value.activeKey === 1) {
      const res = await ConditionSet.value.validateStep();
      itemObj.value.conditionType = 0;
      itemObj.value.sourceActivityId = res.sourceActivityId;
      itemObj.value.activityFNType = res.activityFNType;
      itemObj.value.responseChoice = res.responseChoice || null;
      itemObj.value.compareContent = res?.compareContent || '';
      itemObj.value.compareType = res.compareType;

      itemObj.value.conditionName = sumConditionName(itemObj.value);
    } else if (ConditionSet.value.activeKey === 2) {
      const res = await ConditionSet.value.validateLogic();
      itemObj.value.conditionType = res.conditionType;
      itemObj.value.conditionName = sumConditionName(itemObj.value);
    } else if (ConditionSet.value.activeKey === 3) {
      const res = await ConditionSet.value.validateControlForm();
      itemObj.value.conditionType = 3;
      itemObj.value.bindPropName = res.bindPropName;
      itemObj.value.compareContent = res.compareContent;
      itemObj.value.compareType = res.compareType;
      itemObj.value.conditionName = sumConditionName(itemObj.value);
    }
    updateSelectedItem(conditionList.value, itemObj.value);

    nodeItem.value.condition = conditionList.value[0];
    createMessage.success('操作成功');
    handleAddCancel();
  }
  function handleAddCancel() {
    ConditionSet.value.resetFieldsLogic();
    ConditionSet.value.resetFieldsStep();
    ConditionSet.value.resetFieldsControlForm();
    modalLeft.value = '0px';
    selectedKeys.value = [];
    selectedItemId.value = null;
  }
  function findActivityName(id) {
    const item = modeler.activities.find((i) => i.activityId === id);
    if (item) {
      return item.activityName;
    } else {
      return '';
    }
  }

  // function handleEmpty(){

  // }
  watch(
    () => selectValue.value,
    (val) => {
      conditionItem.value.conditionType = val;
      conditionItem.value.conditionName = logicalConditions[val - 1].label;

      modeler.setActivitiesItem(modeler.getActiveId, 'condition', conditionItem.value);
    },
  );
  const nodeItem = computed(() => modeler.nodeItem);
  watch(
    () => modeler.getActiveId,

    () => {
      conditionItem.value = cloneDeep(nodeItem.value?.condition);

      if (conditionItem.value) {
        conditionList.value = [conditionItem.value];
        setConditionName(conditionList.value);
        selectValue.value = conditionList.value[0]?.conditionType || 1;
      } else {
        conditionList.value = [];
      }
      conditionListBoolean.value = false;
      nextTick(() => {
        conditionListBoolean.value = true;
      });
    },
  );
  // watch(
  //   () => props.tabSiderType,
  //   (val) => {
  //     if (val === 3) {
  //       conditionList.value;
  //     }
  //   },
  // );
</script>

<style lang="less" scoped>
  .condition-setting {
    height: 100%;
    position: relative;
    background: #fff;

    z-index: 555;

    .condition {
      background: #fff;
      width: 100%;
      position: absolute;
      height: 100%;
      z-index: 122;
      overflow: auto;

      .condition-header {
        width: 100%;
        padding: 16px 16px 0 16px;
      }

      .condition-content {
        z-index: 103;
        height: calc(100% - 110px);
        position: absolute;
        width: 100%;

        :deep(.ant-tree-list) {
          .ant-tree-switcher {
            width: 0 !important;

            .anticon {
              display: none;
            }
          }

          .ant-tree-treenode {
            padding: 0 !important;
          }

          .ant-tree-indent {
            width: 0;
          }

          .ant-tree-node-selected,
          .ant-tree-node-content-wrapper:hover {
            background: #f5f6f7 !important;
          }
        }

        .condition-button {
          position: absolute;
          right: 4px;
          top: 7px;
        }
      }
    }

    .condition-modal {
      width: 520px;
      height: 100%;

      background: #ffffff;
      border-radius: 4px 4px 4px 4px;
      opacity: 1;
      position: absolute;
      left: -520px;
      top: 0;
      transition: all 0.5s;
      z-index: -1;

      &::before {
        content: '';
        display: block;
        position: absolute;
        height: 100%;
        top: 0px;
        right: 0px;
        width: 1px;
        background: #e9e9e9;
      }
    }

    .condition-empty {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      margin-top: 76px;

      .text {
        font-size: 12px;
        color: #999999;
      }
    }

    .footer {
      width: 100%;
      height: 72px;
      border-top: 1px solid #f5f6f7;
      background: #ffffff;
      border-radius: 0px 0px 4px 4px;
      opacity: 1;
      position: absolute;
      bottom: 44px;
      z-index: 103;
      right: 1px;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .button {
        margin-right: 26px;
      }
    }

    .mask {
      position: fixed;
      top: 0;
      bottom: 0;
      left: 0;
      right: 392px;
      background-color: rgba(0, 0, 0, 0.45);

      z-index: -100;
    }
  }
</style>
